//
//  FitureCustomDismissAnimation.swift
//  taurus
//
//  Created by 刘艺 on 2021/8/16.
//  Copyright © 2021 com.fiture. All rights reserved.
//

import UIKit

class FitureCustomDismissAnimation: NSObject {
    var config = FitureCustomPresentConfig()
    init(config: FitureCustomPresentConfig) {
        super.init()
        self.config = config
    }
}

extension FitureCustomDismissAnimation: UIViewControllerAnimatedTransitioning {

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        0.25
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

        let fromVC = transitionContext.viewController(forKey: .from)

        let screenBounds = UIScreen.main.bounds
        let finalFrame = CGRect(x: screenBounds.origin.x,
                                y: screenBounds.size.height,
                                width: screenBounds.size.width,
                                height: config.containerViewControllerHeight)

        let containerView = transitionContext.containerView
        /// 模态的背景遮罩
        let maskview = containerView.viewWithTag(1001)

        let duration = self.transitionDuration(using: transitionContext)
        UIView.animate(withDuration: duration) {
            fromVC?.view.frame = finalFrame
            maskview?.alpha = 0
        }completion: { _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            if transitionContext.transitionWasCancelled {
                maskview?.alpha = self.config.maskColorAlpha
            }
        }
    }
}
